package com.dubbo.rpc.discovery;

import com.dubbo.rpc.common.LoadBalanceStrategyEnum;
import com.dubbo.rpc.discovery.strategy.AbstractLoadBalanceStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author liuxin
 * @date 2021/11/1 6:28 下午
 */
@Component
public class LoadBalanceStrategyFactory implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    private Map<LoadBalanceStrategyEnum, AbstractLoadBalanceStrategy> strategyMap;

    @PostConstruct
    public void init() {
        Map<String, AbstractLoadBalanceStrategy> beansOfTypeMap = applicationContext.getBeansOfType(AbstractLoadBalanceStrategy.class);
        strategyMap = beansOfTypeMap.values().stream().collect(Collectors.toMap(AbstractLoadBalanceStrategy::strategy, Function.identity()));
    }

    public AbstractLoadBalanceStrategy selectStrategy(LoadBalanceStrategyEnum loadBalanceStrategy) {
        return strategyMap.get(loadBalanceStrategy);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
